package top.syfy.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * DOM4j方式解析XML文件
 *
 */
public class ParseByDom4j {

    public static void main( String[] args ) throws DocumentException, FileNotFoundException {
        // 创建Reader对象
        SAXReader reader = new SAXReader();
        // 创建输入流
        InputStream in = new FileInputStream(new File("example.xml"));
        // 加载XML文件
        Document document = reader.read(in);
        // 获取根节点
        Element rootElement = document.getRootElement();
        // 遍历节点
        Iterator<Element> iterator = rootElement.elementIterator();;
        while (iterator.hasNext()) {
            // 获取student节点
            Element studentElement = iterator.next();
            // 遍历student节点的属性
            List<Attribute> attributeList = studentElement.attributes();;
            for (Attribute attribute:attributeList) {
                System.out.println("属性: " + attribute.getName() + "=" + attribute.getValue());
            }
            // 获取student节点的子节点
            List<Element> studentSubElementList = studentElement.elements();;
            // 遍历student节点的子节点
            for (Element sub:studentSubElementList) {
                System.out.println("节点: " + sub.getName() + "=" + sub.getStringValue());
            }
            System.out.println("=========================");
        }

    }
}
